<?php

namespace App\Http\Controllers\Common;

use App\Http\Controllers\BaseController;
use App\Http\Validate\Common\CommonValidate;
use App\Models\ChatGroup\ChatGroupModel;
use App\Models\ChatGroup\ChatGroupUserModel;
use App\Models\Common\HolidayModel;
use App\Service\Common\CommonService;
use App\Service\Common\MerchantService;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;


class CommonController extends BaseController
{
    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function privateUpload(Request $request): JsonResponse
    {
        $uploadedFile = $request->file('file');
        if (!$uploadedFile instanceof UploadedFile) {
            return $this->fail(0, '请上传文件');
        }
        return $this->success(CommonService::privateUpload($uploadedFile));
    }

    /**
     * 食品许可证识别
     *
     * @param Request $request
     * @return JsonResponse
     * @throws Exception
     */
    public function foodProduceLicenseRecognize(Request $request): JsonResponse
    {
        $uploadedFile = $request->file('file');
        if (!$uploadedFile instanceof UploadedFile) {
            return $this->fail(0, '请上传文件');
        }
        $expect = (string)$request->get('expect', '');
        if ($expect && !in_array($expect,['ignoreOcrError'])){
            return $this->fail(0, 'expect参数异常');
        }
        return $this->success(CommonService::foodProduceLicenseRecognize($uploadedFile, $expect));
    }

    /**
     * 银行卡识别
     *
     * @param Request $request
     * @return JsonResponse
     * @throws Exception
     */
    public function recognizeBankCard(Request $request): JsonResponse
    {
        $uploadedFile = $request->file('file');
        if (!$uploadedFile instanceof UploadedFile) {
            return $this->fail(0, '请上传文件');
        }
        return $this->success(CommonService::recognizeBankCard($uploadedFile));
    }

    /**
     * 获取表的最大id
     * @param Request $request
     * @return JsonResponse
     */
    public function getMaxId(Request $request): JsonResponse
    {
        $table = $request->get('table', '');

        $this->validate($request, [
            'table' => [
                'required',
                'string',
                Rule::in([
                    'cruise_project_category',
                    'cruise_task_project',
                    'cruise_template',
                    'cruise_template_position'
                ])
            ]
        ]);

        return $this->success(['id' => DB::table($table)->max('id')]);
    }

    /**
     * 节假日信息
     * @param Request $request
     * @return JsonResponse
     */
    public function holiday(Request $request)
    {
        $startDate = $request->get('startDate', Carbon::now()->startOfMonth()->toString());
        $endDate   = $request->get('endDate', Carbon::now()->endofMonth()->toString());

        $startDate = (int)date('Ymd', strtotime($startDate));
        $endDate   = (int)date('Ymd', strtotime($endDate));

        $holidays = HolidayModel::getHolidays($startDate, $endDate);
        return $this->success($holidays->toArray());
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public function devicePushBind(Request $request): JsonResponse
    {
        $params = CommonValidate::devicePushBindValidate($request->all());
        CommonService::devicePushBind($params);
        return $this->success();
    }

    /**
     * 快递查询接口
     * @param Request $request
     * @return JsonResponse
     */
    public function logisticsQuery(Request $request): JsonResponse
    {
        $this->validate(
            $request, [
                'company' => 'required|string',
                'number'  => 'required|string',
                'sign'    => 'required|string',
            ]
        );
        $company = $request->get('company', '');//快递公司字母简写：不知道可不填 95%能自动识别，填写查询速度会更快
        $number  = $request->get('number', ''); //快递单号
        $sign    = $request->get('sign', '');   //签名

        $data = CommonService::logisticsQuery($company, $number, $sign);
        if (!count($data['result']['list'] ?? [])) {
            $data = null;
        }
        return $this->success($data);
    }

    /**
     * 按天获取工作日期
     * @param Request $request
     * @return JsonResponse
     */
    public function getWorkDateByDays(Request $request): JsonResponse
    {
        $days = (int)$request->get('days', 0);
        $date = $request->get('date', date('Ymd', time()));
        return $this->success(CommonService::getWorkDateByDays($days, $date));
    }


    /**
     * 节假日&工作时间信息
     * @param Request $request
     * @return JsonResponse
     */
    public function isWorkDayTime(Request $request): JsonResponse
    {
        $dataInt = (int)$request->get('t', time());
        $data = date("Y-m-d H:i:s", $dataInt);
        list($isWorkDay, $isWorkDayTime) = HolidayModel::checkWorkTime($data);
        return $this->success([
            'isWorkDay'     => (int)$isWorkDay,
            'isWorkDayTime' => (int)$isWorkDayTime,
        ]);
    }

    /**
     * app切换门店后，相关配置获取
     * @param Request $request
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function configByShopId(Request $request)
    {
        $shopId = $request->header('shopId');
        $userId = getRmsUserId();

        $group = ChatGroupUserModel::checkAppUserIn($shopId, $userId, ChatGroupModel::TYPE_CUSTOMER_SERVE);

        $data = [
            'groupId'  => $group->id ?? 0, // 客服群聊id
            'feeOrders' => MerchantService::getNoticeList((int)$shopId)
        ];

        return $this->success($data);
    }

    public function getAmapWebJsApi(Request $request)
    {
        $this->validate($request, [
           'errorKey' => 'string'
        ]);
        $errorKey = $request->post('errorKey');

        return $this->success(CommonService::getAmapWebJsApi($errorKey));
    }

    /**
     * 查询门店属性配置项
     * @param Request $request
     * @return JsonResponse
     */
    public function getShopAttributeData(Request $request): JsonResponse
    {
        return $this->success(CommonService::getShopAttributeData('shopType'));
    }

    /**
     * 社保卡识别
     *
     * @param Request $request
     * @return JsonResponse
     * @throws Exception
     */
    public function recognizeSocialSecurityCard(Request $request): JsonResponse
    {
        $uploadedFile = $request->file('file');
        if (!$uploadedFile instanceof UploadedFile) {
            return $this->fail(0, '请上传文件');
        }
        return $this->success(CommonService::recognizeSocialSecurityCard($uploadedFile));
    }
}
